package backend.db;

/**
 * Represents a table in the database.<br />
 * Assumes it has at least 1 column.
 */
public class Table {
  final String name;
  private final Column[] columns;
  private final String[] primaryKey;
  
  public Table(final String _name, final Column... _columns) {
    this(_name, null, _columns);
  }
  
  public Table(final String _name, final String[] _primaryKey, final Column... _columns) {
    name = _name;
    columns = _columns;
    primaryKey = _primaryKey;
  }
  
  public String getCreateSQL() {
    if (columns.length < 1)
      throw new AssertionError("Trying to create a table with no columns");
    final StringBuilder $ = new StringBuilder("CREATE TABLE IF NOT EXISTS ").append(name).append(" (")
        .append(columns[0]);
    for (int i = 1; i < columns.length; ++i)
      $.append(", ").append(columns[i]);
    if (null != primaryKey && primaryKey.length > 0) {
      $.append(", PRIMARY KEY (").append(primaryKey[0]);
      for (int i = 1; i < primaryKey.length; ++i)
        $.append(", ").append(primaryKey[i]);
      $.append(")");
    }
    $.append(") ENGINE = INNODB;");
    return $.toString();
  }
  
  public String getDropSQL() {
    return "DROP TABLE IF EXISTS " + name + ";";
  }
  
  Column getColumn(final String colName) {
    for (final Column c : columns)
      if (c.name.equals(colName))
        return c;
    return null;
  }
  
  Cell[] makeCellArray(final Object... values) {
    if (columns.length != values.length)
      throw new IllegalArgumentException("Number of values doesn't match table");
    final Cell[] $ = new Cell[columns.length];
    for (int i = 0; i < columns.length; ++i)
      $[i] = new Cell(columns[i], values[i]);
    return $;
  }
}
